<?php

namespace app\admin\controller;

use app\common\controller\Backend;
// use app\common\library\Email;
use app\admin\model\Reserve as ReserveModel;
use think\Exception;
use think\Validate;
use app\admin\model\ReserveSetting;
use app\common\model\Config;
// use think\Db;

/**
 * 预约数量
 *
 * @icon   fa fa-cogs
 * @remark 可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除
 */
class Reserve extends Backend
{

    /**
     * @var \app\common\model\Config
     */
    protected $model = null;
    protected $noNeedRight = ['check', 'rulelist'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Reserve');
        ReserveModel::event('before_write', function ($row) {
            if (isset($row['name']) && $row['name'] == 'name' && preg_match("/fast" . "admin/i", $row['value'])) {
                throw new Exception(__("Reserve number incorrect"));
            }
        });
    }

    /**
     * 查看
     */
    public function index()
    {

        // $id = 18;
        // $config = Config::get($id);
        // echo $config['value'];
        // echo config('site.time');
        // exit();
        $siteList = [];
        $groupList = ReserveModel::getGroupList();
        //var_dump($groupList);exit();
        foreach ($groupList as $k => $v)
        {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];                
        }
        //var_dump($this->model->all());exit();

        foreach ($this->model->all() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            // 只取name 为reservesetting 和 time的列表。
            if($value['name']=='reservesetting'||$value['name']=='time'||$value['name']=='begin_time'||$value['name']=='begin_fen'||$value['name']=='end_time'||$value['name']=='end_fen')
            {
                //echo $value['name']."<br/>";
                $value['title'] = __($value['title']);
                if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                    $value['value'] = explode(',', $value['value']);
                }
                $value['content'] = json_decode($value['content'], true);
                $value['tip'] = htmlspecialchars($value['tip']);
                $siteList[$v['group']]['list'][] = $value;
            }
        }
        //exit();
        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }
        //var_dump($siteList);exit();
        //["Please select","1:00","2:00","3:00","4:00","5:00","6:00","7:00","8:00","9:00","10:00","11:00","12:00","13:00","14:00","14:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","24:00"]

        // ["Please select","05","10","15","20","25","30","35","40","45","50","55","00"]


        $this->view->assign('siteList', $siteList);
        $this->view->assign('groupList', ReserveModel::getGroupList());

        return $this->view->fetch();
    }

    

    /**
     * 编辑
     * @param null $ids
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
            $row = $this->request->post("row/a", [], 'trim');

            if ($row) {
                $configList = [];
                foreach ($this->model->all() as $k=> $v) {
                    if (isset($row[$v['name']])) {
                        $value = $row[$v['name']];
                        if (is_array($value) && isset($value['field'])) {
                            $value = json_encode(BookModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
                        } else {
                            $value = is_array($value) ? implode(',', $value) : $value;
                        }
                        // if($v['type']=='select')
                        // {
                        //     $v['name']
                        // }
                        // echo $k."###".$v['name']."<br>";
                        $v['value'] = $value;
                        $configList[] = $v->toArray();
                    }
                }
                //exit('######');
                try {
                    $this->model->allowField(true)->saveAll($configList);
                    
                    //获取设置的预约数量，预约时间
                    $info = $this->model->where('name', 'reservesetting')->find();

                    //先统计浴池当中是否有有人数
                    //已预约还未过期的,未进入，未离开
                    $count = \app\admin\model\ReserveRecord::where(['states'=>1,'into_states'=>0,'leave_states'=>0])->count();

                    //已预约，已进入，还未过期，还未离开
                    $into_count = \app\admin\model\ReserveRecord::where(['states'=>1,'into_states'=>1,'leave_states'=>0])->count();

                    $finy = $count + $into_count;

                    $params = array(
                        'reserve_number'  => $info['value'],
                        'add_time'  => time(),
                        'reserved_number'  => $info['value']-$finy,
                    );

                    //更新的固定表reserve_setting
                    $id = 1;
                    $setting = ReserveSetting::get($id);
                    $setting->save($params);

                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                try {
                    $this->refreshFile();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 刷新配置文件
     */
    protected function refreshFile()
    {
        $config = [];
      
        foreach ($this->model->all() as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $config[$value['name']] = $value['value'];
        }
        //extra/site.php 写序列
        file_put_contents(
            APP_PATH . 'extra' . DS . 'site.php',
            '<?php' . "\n\nreturn " . var_export($config, true) . ";"
        );
    }

    /**
     * 检测配置项是否存在
     * @internal
     */
    public function check()
    {
        $params = $this->request->post("row/a");
        if ($params) {
            $config = $this->model->get($params);
            if (!$config) {
                return $this->success();
            } else {
                return $this->error(__('Name already exist'));
            }
        } else {
            return $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 规则列表
     * @internal
     */
    public function rulelist()
    {
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $keyValue = $this->request->request("keyValue", "");

        $keyValueArr = array_filter(explode(',', $keyValue));
        $regexList = \app\common\model\Config::getRegexList();
        $list = [];
        foreach ($regexList as $k => $v) {
            if ($keyValueArr) {
                if (in_array($k, $keyValueArr)) {
                    $list[] = ['id' => $k, 'name' => $v];
                }
            } else {
                $list[] = ['id' => $k, 'name' => $v];
            }
        }
        return json(['list' => $list]);
    }

    // /**
    //  * 发送测试邮件
    //  * @internal
    //  */
    // public function emailtest()
    // {
    //     $row = $this->request->post('row/a');
    //     $receiver = $this->request->post("receiver");
    //     if ($receiver) {
    //         if (!Validate::is($receiver, "email")) {
    //             $this->error(__('Please input correct email'));
    //         }
    //         \think\Config::set('site', array_merge(\think\Config::get('site'), $row));
    //         $email = new Email;
    //         $result = $email
    //             ->to($receiver)
    //             ->subject(__("This is a test mail"))
    //             ->message('<div style="min-height:550px; padding: 100px 55px 200px;">' . __('This is a test mail content') . '</div>')
    //             ->send();
    //         if ($result) {
    //             $this->success();
    //         } else {
    //             $this->error($email->getError());
    //         }
    //     } else {
    //         return $this->error(__('Invalid parameters'));
    //     }
    // }
}
